package de.arndt_plc.wakeonmagic;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;

import java.io.IOException;
import java.net.UnknownHostException;
import java.util.ArrayList;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p/>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class WakeOnMagicIntentService extends IntentService {

    public static final String TAG = WakeOnMagicIntentService.class.getSimpleName();

    public static final String ACTION_WAKE_PC = "de.arndt_plc.wakeonmagic.action.WAKE_PC";
    public static final String EXTRA_MAC = "MAC";
    public static final String EXTRA_IP = "IP";

    public WakeOnMagicIntentService() {
        super("WakeOnMagicIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_WAKE_PC.equals(action)) {
                final String mac = intent.getStringExtra(EXTRA_MAC);
                final String ip = intent.getStringExtra(EXTRA_IP);
                Log.d(TAG, String.format("Receive intent: MAC:%s IP:%s", mac, ip));
                handleActionWakePc(mac, ip);
            }
        }
    }

    private void handleActionWakePc(String mac, String broadcast_ip) {
        try {
            WakeOnLan wol = new WakeOnLan(broadcast_ip);
            wol.wake(mac);
        } catch (IOException e) {
            Log.d(TAG, e.getMessage(), e);
        } catch (IllegalArgumentException e) {
            Log.d(TAG, "Wrong parameter: mac: " + mac + " ip: " + broadcast_ip + " (" + e.getMessage() + ")", e);
        }
    }

}
